// 运行时配置
import { RequestOptions, RequestConfig, RunTimeLayoutConfig, history } from "@umijs/max";
import { fetchUserInfo, logout } from "./services/user";
import { UserInfo } from "./interfaces/user";
import { AxiosResponse } from "axios";
import { message } from 'antd';

import React from 'react';
import RightRenderContent from '@/components/layout/RightRenderContent';
import MenuCard from '@/components/layout/MenuCard';

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState() {
  const userInfo:UserInfo = await fetchUserInfo();
  return userInfo;
}

export const request: RequestConfig = {
  timeout: 2000,
  requestInterceptors: [
    (config: RequestOptions) =>
      {
        const newOptions: RequestOptions = { ...config };
        const token = localStorage.getItem('token');
        if (token) {
          newOptions.headers = {
            ...newOptions.headers,
            'Authorization': 'Bearer ' + token,
          };
        }
        return newOptions;
      },
  ],
  responseInterceptors: [
    (response) => {
      const { data } = response as AxiosResponse;
      if (!data.success) {
        message.error(data.message);
      }
      if (data.code === 1003) {
        const path = history.location.pathname !== '/login';
        history?.push('/login?redirect=' + (path ? history.location.pathname : '/'));
      }
      return response;
    },
  ]
}


export const layout: RunTimeLayoutConfig = () => {
  return {
    logo: 'https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg',
    menu: {
      locale: false,
      collapsedShowGroupTitle: true,
    },
    siderMenuType: "group",
    headerTitleRender:(logo, title, _) => {
      const defaultDom = (
        <a>
          {logo}
          {title}
        </a>
      );
      if (typeof window === 'undefined') return defaultDom;
      if (document.body.clientWidth < 1400) {
        return defaultDom;
      }
      if (_.isMobile) return defaultDom;
      return (
        <>
          {defaultDom}
          <MenuCard />
        </>
      );
    },
    menuFooterRender: (props) => {
      if (props?.collapsed) return undefined;
      return (
        <div
          style={{
            textAlign: 'center',
            paddingBlockStart: 12,
          }}
        >
          <div>© 2024 萌心芽</div>
          <div>by 首席技术架构师-夜声</div>
        </div>
      );
    },

    fixSiderbar: true,
    layout: 'mix',
    splitMenus: true,

    logout: async () => {
      await logout();
      localStorage.removeItem('token');
      history?.push('/login');
    },
    rightRender: RightRenderContent,
  };
};
